<?php

class Auditable extends Doctrine_Template_Versionable
{

	protected $_options = array(
		'version' => array(	'name'   => 'version',
							'type'   => 'integer',
							'length' => 2,
							'options' => array()),
		'generateRelations'	=> true,
		'tableName'			=> false,
		'generateFiles'		=> false,
		'auditLog'			=> true,
		'deleteVersions'	=> true,
		'listener'			=> 'AuditableListener',
		'relations'			=> array()
	);

	public function __construct(array $options = array())
	{
		$this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
		$this->_plugin = new AuditableLog($this->_options);
	}

	public function setUp()
	{
		if ($this->_plugin->getOption('auditLog'))
		{
			$this->_plugin->initialize($this->_table);

			//crea tablas de version para las relaciones indicadas en actAs (relacion muchos)
			foreach ($this->_options['relations'] as $relationName)
			{
				//se busca refClass para crear la tabla de version
				$relation = $this->_table->getRelation($relationName);
				if ($relation instanceof Doctrine_Relation_Association)
					$relationTable = $this->_table->getRelation($relationName)->getAssociationTable();
				else
					$relationTable = Doctrine_Core::getTable($relationName);
					

				$relationOptions = $this->_options;

				//no agrega columnas de usuario y fecha para la version de la relacion
				$relationOptions['generateLog'] = false;

				$relationPlugin = new AuditableLog($relationOptions);
				$relationPlugin->initialize($relationTable);
			}
		}

		$version = $this->_options['version'];
		$this->hasColumn($version['name'], $version['type'], $version['length'], $version['options']);

		$listener = $this->_plugin->__get('listener'); //schema.yml
		if ($listener == null)
			$listener = $this->_options['listener'];

		$this->addListener(new $listener($this->_plugin));
	}

	public static function getAuditableModels()
	{
		$schema = sfYaml::load(sfConfig::get('sf_root_dir') . '/config/doctrine/schema.yml');
		$models = array();
		foreach ($schema as $name => $model)
		{
			if (isset($model['actAs']))
			{
				if (in_array('Auditable', $model['actAs']) || array_key_exists('Auditable', $model['actAs']))
					$models[$name] = $name;
			}
		}

		return $models;
	}

}
